package com.study.mybatis.service;

import org.apache.ibatis.session.SqlSession;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;

///@Aspect
//@Component
public class SqlExecutionTimeoutAspect {
    @Around("execution(* org.apache.ibatis.session.SqlSession+.execute*(..))")
    public Object setSqlTimeout(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取当前线程的 SqlSession
        SqlSession session = null;
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof SqlSession) {
                session = (SqlSession) arg;
                break;
            }
        }
        if (session != null) {
            // 设置超时时间，这里以30秒为例
            session.getConnection().setNetworkTimeout(Executors.newFixedThreadPool(1), 2000);
        }
        try {
            // 继续执行原始方法
            return joinPoint.proceed();
        } finally {
            if (session != null) {
                // 清理或还原超时设置（如果需要）
            }
        }
    }
}
